﻿Imports System.IO.Ports
Imports System.Text.RegularExpressions
Imports System.Data.SqlClient
Imports System.Net.Mail

Public Class engine
#Region "SMS"
    Dim rcvdata As String = ""
    Public WithEvents SerialPort1 As SerialPort
    Public DeviceGood As Boolean = True
    Private Sub Responder(ByVal indata As String)
        rcvdata &= indata
        'MsgBox(rcvdata)
        ' ReadMsg(SerialPort1, rcvdata)
        If rcvdata.Contains("OK") Then
            If rcvdata.Contains("CPMS") Then
                GoTo Read
            End If
        ElseIf rcvdata.Contains("AT") Then
            If rcvdata.Contains("CPMS") Then
                GoTo Read
            End If
        ElseIf rcvdata.Contains("CPMS") Then
Read:
            ReadMsg(SerialPort1, rcvdata)
        ElseIf rcvdata.Contains("CMGS") Then
            MsgBox(rcvdata)
        Else
            MsgBox("Check Device or Settings!" & rcvdata, MsgBoxStyle.Critical)
            DeviceGood = False
        End If
        'MsgBox(rcvdata)
    End Sub
    Private Sub serialport1_datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim datain As String = ""
        Try
Read:
            Dim numbytes As Integer = SerialPort1.BytesToRead
            For i As Integer = 1 To numbytes
                datain &= Chr(SerialPort1.ReadChar)
            Next
            Responder(datain)
        Catch ex As Exception
            Append(ex.Message)
            GoTo Read
        End Try
    End Sub
    Public Sub InsertAllMessages()
        Try
            'Open Port
            Dim mainport As SerialPort
            SyncLock Me
                mainport = OpenPort(SerialPort1)
            End SyncLock
            If mainport.IsOpen Then
                Append("Initializing device completed")
            End If

            Append("Reading all messages from gsm")
            With mainport
                rcvdata = ""
                .Write("AT" & vbCrLf)
                Threading.Thread.Sleep(1)
                .Write("AT+CMGF=1" & vbCrLf)
                Threading.Thread.Sleep(1)
                .Write("AT+CPMS=""SM""" & vbCrLf)
                Threading.Thread.Sleep(1)
                .Write("AT+CMGL=""ALL""" & vbCrLf)
                Threading.Thread.Sleep(2000)
            End With
        Catch ex As Exception
            Append(ex.Message)
        End Try
    End Sub
    Public Sub InsertUnreadMessages()
        Try
            'Open Port
            Dim mainport As SerialPort '= SerialPort1
            SyncLock Me
                mainport = OpenPort(SerialPort1)
            End SyncLock

            With mainport
                rcvdata = ""
                .Write("AT" & vbCrLf)
                Threading.Thread.Sleep(1)
                .Write("AT+CMGF=1" & vbCrLf)
                Threading.Thread.Sleep(1)
                '.Write("AT+CPMS=""SM""" & vbCrLf)
                .Write("AT+CPMS=""SM""" & vbCrLf)
                Threading.Thread.Sleep(1)
                '.Write("AT+CMGL=""REC UNREAD""" & vbCrLf)
                .Write("AT+CMGL=""ALL""" & vbCrLf)
                Threading.Thread.Sleep(1)
                .Write("AT+CMGD=1,4" & vbCrLf)
                Threading.Thread.Sleep(2000)
            End With
        Catch ex As Exception
            Append(ex.Message)
        End Try
    End Sub
    Public Function OpenPort(port As SerialPort) As SerialPort
        Try
            'Append("Checking device availability")
            If port.IsOpen Then
                port.Close()
                GoTo OpenPort
            Else
OpenPort:
                'Append("Initializing device..")
                Try
                    With port
                        'MsgBox(My.Settings.Portname)
                        .PortName = My.Settings.Portname
                        'MsgBox(.PortName)
                        .BaudRate = My.Settings.BitsPerSecond
                        .Parity = Parity.None
                        .DataBits = My.Settings.Databits
                        .StopBits = StopBits.One
                        .Handshake = Handshake.None
                        .RtsEnable = True
                        .ReceivedBytesThreshold = 1
                        .NewLine = vbCr
                        .RtsEnable = True
                        .DtrEnable = True
                        .ReadTimeout = 1000
                        SyncLock Me
                            .Open()
                            Return port
                        End SyncLock
                    End With
                Catch ex As Exception
                    Append(ex.Message)
                    MsgBox(ex.Message)
                    Return port
                End Try
            End If
        Catch ex As Exception
            Append(ex.Message)
        End Try
        Return port
    End Function
    Private Sub ReadMsg(port As SerialPort, msg As String)
        Try
            'Append("Extracting messages")
            Dim lineoftext As String
            Dim i As Integer
            Dim arytextfile() As String
            lineoftext = msg.ToString
            arytextfile = Split(lineoftext, "+CMGL", , CompareMethod.Text)
            For i = 1 To UBound(arytextfile)
                Dim input As String = arytextfile(i)
                port.Write("AT+CMGD=" & GetMiddleString(input, ": ", ",") & vbCrLf)
                Threading.Thread.Sleep(3000)
                AddtItemtoList(input, port)
            Next
        Catch ex As Exception
            Append(ex.Message)
        End Try
    End Sub
    Function CheckForAlphaCharacters(ByVal StringToCheck As String) As Boolean
        'For i = 0 To StringToCheck.Length - 1
        '    If Char.IsLetter(StringToCheck.Chars(i)) Then
        '        Return True
        '    End If
        'Next
        If StringToCheck.Contains(" ") Then
            Return True
        End If
        Return False
    End Function
    Sub AddtItemtoList(input As String, serialport1 As SerialPort)
        Try
            Dim result() As String
            Dim pattern As String = "(,"")|("","")"
            result = Regex.Split(input, pattern)

            Dim Status, Sender, time, message As String
            Dim concatmessage As String()
            concatmessage = Split(result(6), """")

            time = concatmessage(0).Replace("'", "")
            message = concatmessage(1).Replace(vbCrLf & "OK", "")
            message = message.TrimStart
            message = message.TrimEnd
            Try
                Dim com As String = ""
                For x = 0 To message.Length - 1 Step 2
                    Dim k As String = message.Substring(x, 2)
                    com &= System.Convert.ToChar(System.Convert.ToUInt32(k, 16)).ToString()
                Next
                message = com
            Catch ex As Exception

            End Try

            Status = result(2)
            Sender = result(4).Replace("""", "")
            Sender = Sender.Replace(",", "")
            If CheckDuplicate(Sender, time) = False Then
                'Add
                Try
                    Dim insert_cmd As SqlCommand
                    Dim insert_con As SqlConnection
                    insert_con = New SqlConnection(My.Settings.connectionstring)
                    insert_con.Open()
                    insert_cmd = New SqlCommand("INSERT INTO recieved ([sms_from],[sms_date],[sms_message]) VALUES (@sms_from,@sms_date,@sms_message)", insert_con)
                    insert_cmd.Parameters.AddWithValue("sms_from", Sender)
                    insert_cmd.Parameters.AddWithValue("sms_date", time)
                    insert_cmd.Parameters.AddWithValue("sms_message", message)
                    insert_cmd.ExecuteNonQuery()

                    Append(input.Trim.Replace(vbCrLf, " "))
                Catch ex As Exception
                    'APPENDLOGS
                    'MsgBox(ex.Message)

                End Try
            End If
        Catch ex As Exception
            Append(ex.Message)
        End Try
    End Sub
    Function CheckDuplicate(KeyString As String, KeyString2 As String) As Boolean
        Dim constring As String = My.Settings.connectionstring
        Try
            Using con As New SqlConnection(constring)
                Dim cmd As New SqlCommand
                cmd.Connection = con
                cmd.CommandText = "SELECT * FROM [recieved] WHERE [sms_from]=@sms_from and [sms_date]=@sms_date "
                cmd.Parameters.AddWithValue("@sms_from", KeyString)
                cmd.Parameters.AddWithValue("@sms_date", KeyString2)
                cmd.CommandType = CommandType.Text
                con.Open()
                Dim checker As SqlDataReader
                checker = cmd.ExecuteReader()
                If checker.HasRows Then
                    con.Close()
                    checker.Close()
                    Return True
                Else
                    checker.Close()
                    con.Close()
                    Return False
                End If
            End Using
        Catch ex As Exception

            Return True
        End Try
    End Function

    Sub SendMessage(Recipient As String, message As String)
        Try
            Dim mainport As SerialPort
            SyncLock Me
                mainport = OpenPort(SerialPort1)
            End SyncLock
            'If mainport.IsOpen Then
            '    Append("Initializing device completed")
            'End If
            Dim FinaleMessage As String = message
            With mainport
                .Write("AT" & vbCrLf)
                Threading.Thread.Sleep(100)
                .Write("AT+CMGF=1" & vbCrLf)
                Threading.Thread.Sleep(100)
                .Write("AT+CMGS=" & Chr(34) & Recipient & Chr(34) & vbCrLf)
                .Write(Chr(13) & message & Chr(26) & vbCrLf)
                Threading.Thread.Sleep(100)
                MsgBox("AT+CMGS=" & Chr(34) & Recipient & Chr(34) & vbCrLf & Chr(13) & message & Chr(26) & vbCrLf)
            End With

            'If rcvdata.ToString.Contains(">") Then
            '    MsgBox("Message Sent", MsgBoxStyle.Information, "SMS")
            'Else
            '    MsgBox("Got some error")
            'End If


        Catch ex As Exception
            Append(ex.Message)
        End Try
    End Sub

    Function Spinner(Spinners As String) As String

    End Function
#End Region
#Region "Events"
    Public Sub Append(Message As String)
        Dim Date_ As DateTime = DateTime.Now
        Dim format As String = "yyyyMMdd"
        Console.WriteLine(Date_.ToString(format))
        Try
rety:
            Dim FILE_NAME As String = My.Application.Info.DirectoryPath & "\EVENTS_" & Date_.ToString(format) & ".txt"
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
            Dim timestamp As String
            timestamp = Now.ToString
            objWriter.WriteLine(timestamp & "|" & Message)
            objWriter.Close()
        Catch ex As Exception
            GoTo rety
        End Try
    End Sub
#End Region
#Region "Mail"
    Public Keylist As New ArrayList
    Public MailValue As New ArrayList
    Sub SendMail(sender As String, timesent As String, message As String)
        'Built Mailing List
        If System.IO.File.Exists(My.Settings.maillistloc) = True Then
            Dim objReader As New System.IO.StreamReader(My.Settings.maillistloc)
            Do While objReader.Peek() <> -1
                Dim spliter As String()
                spliter = objReader.ReadLine().Split("|")
                Keylist.Add(spliter(0))
                MailValue.Add(spliter(1))
            Loop
        End If

        Dim ListofMail As New ArrayList
        Dim Splitmsg As String()
        Splitmsg = message.Split(" ")
        Dim ComparableKey As String = Splitmsg(0)


        Dim Indx As Integer = 0
        For Each item As String In Keylist
            If item.ToUpper = ComparableKey.ToUpper Then
                ListofMail.Add(MailValue(Indx))
            ElseIf item.ToUpper.Contains(ComparableKey.ToUpper) Then
                ListofMail.Add(MailValue(Indx))
            End If
            Indx += 1
        Next

        Dim mail As New MailMessage
        Try
            Append("Setting Up Mail..")
            mail.Subject = "SMS Feedback"
            For Each item As String In ListofMail
                mail.To.Add(item)
            Next
            mail.From = New MailAddress("no-reply@roaster.com.ph")
            message = "From: " & sender & vbCrLf & message

            If My.Settings.mailenableheader = True Then
                mail.Body = My.Settings.mailheader & vbCrLf & vbCrLf & message.Replace(ComparableKey, "")
            Else
                mail.Body = message.Replace(ComparableKey, "")
            End If
            Append("Configuring Credentials...")
            Dim SMTP As New SmtpClient(My.Settings.smtpserver)
            SMTP.EnableSsl = My.Settings.smtpusessl
            SMTP.Credentials = New System.Net.NetworkCredential(My.Settings.smptuser, My.Settings.smtppassword)
            SMTP.Port = Integer.Parse(My.Settings.smptport)
            SMTP.UseDefaultCredentials = True
            Append("Sending Mail from " & sender & " to Guest Mail Service Success")
            SMTP.Send(mail)
        Catch ex As Exception
            Append(ex.Message)
        End Try
    End Sub
#End Region
#Region "MISC"
    Function GetMiddleString(StringInput As String, FirstDelimeter As String, LastDelimiter As String) As String
        Dim ReturnString As String = "ERROR"
        Try
            Dim Split1 As String()
            Split1 = StringInput.Split(FirstDelimeter)
            Dim Split2 As String()
            Split2 = Split1(1).Split(LastDelimiter)
            ReturnString = Split2(0)
        Catch ex As Exception

        End Try
        Return ReturnString
    End Function

#End Region

End Class
